package com.song.druid.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSONObject;
import com.song.druid.annotation.ListGroupVaild;
import com.song.druid.api.Insert;
import com.song.druid.api.PageQuery;
import com.song.druid.api.Update;
import com.song.druid.model.UserModel;
import com.song.druid.param.BatchInsertParam;
import com.song.druid.param.UserQueryParam;
import com.song.druid.result.ResultEntity;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.GetMapping;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.song.druid.entity.UserInfo;
import com.song.druid.service.UserInfoService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestBody;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.ObjectUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.Serializable;
import java.util.Map;

/**
* <p>
    * 用户信息 控制器
    * </p>
*
* @author song
* @since 2023-11-09
*/
@Api(tags = {"用户信息 控制器"})
@RestController
@RequestMapping("/user_info")
public class UserInfoController {

    @Autowired
    UserInfoService userInfoService;

    /**
    * 分页查询数据
    *
    * @author song
    * @Date 2023-11-09
    */
    @ApiOperation(value = "按条件分页检索用户信息",notes = "按条件分页检索用户信息")
    @GetMapping(value = "/pageList")
    public ResultEntity<Page<UserInfo>> pageList(@Validated(PageQuery.class) UserQueryParam userQueryParam) {
        Page<UserInfo> page = new Page<>(userQueryParam.getPageNum(), userQueryParam.getPageSize());
        LambdaQueryWrapper<UserInfo> lambda = lambdaQueryWrapper(userQueryParam);
        return ResultEntity.success(userInfoService.page(page,lambda));
    }

    @ApiOperation(value = "按条件分页检索用户信息",notes = "按条件分页检索用户信息")
    @GetMapping(value = "/queryPage")
    public ResultEntity queryPage(@Validated(PageQuery.class) UserQueryParam userQueryParam){
        return ResultEntity.success(userInfoService.queryPage(userQueryParam));
    }

    /**
    * 查询数据List
    *
    * @author song
    * @Date 2023-11-09
    */
    @ApiOperation(value = "查询全部用户信息",notes = "查询全部用户信息")
    @GetMapping(value = "/list")
    public ResultEntity<List<UserInfo>> list(@Validated UserQueryParam userQueryParam) {
        LambdaQueryWrapper<UserInfo> lambda = lambdaQueryWrapper(userQueryParam);
        List<UserInfo> userInfoList = userInfoService.list(lambda);
        return ResultEntity.success(userInfoList);
    }

    /**
    * 用户信息新增
    *
    * @author song
    * @Date 2023-11-09
    */
    @ApiOperation(value = "新增用户信息",notes = "新增用户信息")
    @PostMapping(value = "/add")
    public ResultEntity add(@Validated(Insert.class) @RequestBody UserInfo userInfo) {
        userInfoService.saveSensitive(userInfo);
        return ResultEntity.success();
    }

    /**
    * 用户信息修改
    *
    * @author song
    * @Date 2023-11-09
    */
    @ApiOperation(value = "修改用户信息",notes = "修改用户信息")
    @PostMapping(value = "/update")
    public ResultEntity edit(@Validated(Update.class) @RequestBody UserInfo userInfo) {
        userInfoService.updateByIdSensitive(userInfo);
        return ResultEntity.success();
    }

    /**
    * 删除用户信息
    *
    * @author song
    * @Date 2023-11-09
    */
    @ApiOperation(value = "按id删除用户信息",notes = "按id删除用户信息")
    @PostMapping(value = "/delete")
    public ResultEntity delete(@RequestParam Serializable id) {
        userInfoService.removeById(id);
        return ResultEntity.success();
    }


    /**
    * 根据id查询用户信息
    *
    * @author song
    * @Date 2023-11-09
    */
    @ApiOperation(value = "根据id查询用户信息",notes = "根据id查询修改用户信息")
    @GetMapping(value = "/detail")
    public ResultEntity<UserInfo> detail(@RequestParam Serializable id) {
        UserInfo userInfo = userInfoService.getById(id);
        return ResultEntity.success(userInfo);
    }

    @ApiOperation(value = "批量新增",notes = "批量新增")
    @PostMapping(value = "/saveBatch")
    public ResultEntity saveBatch(@Validated(Insert.class) @RequestBody BatchInsertParam batchInsertParam){
        userInfoService.saveBatchSensitive(batchInsertParam.getDatas());
        return ResultEntity.success();
    }

    @ApiOperation(value = "批量更新",notes = "批量更新")
    @PostMapping(value = "/updateBatch")
    public ResultEntity updateBatch(@RequestBody List<UserInfo> userInfos){
        userInfoService.updateBatchByIdSensitive(userInfos);
        return ResultEntity.success();
    }

    @ApiOperation(value = "测试接口",notes = "测试接口")
    @PostMapping(value = "/sout")
    public ResultEntity sout(@RequestBody UserInfo userInfo){
        System.out.println(userInfo);
        return ResultEntity.success(userInfo);
    }

    public LambdaQueryWrapper<UserInfo> lambdaQueryWrapper(UserQueryParam userQueryParam){
        LambdaQueryWrapper<UserInfo> lambda = new QueryWrapper<UserInfo>().lambda();
        lambda.orderByDesc(UserInfo::getCreateTime);
        if (userQueryParam == null) {
            return lambda;
        }
        if(ObjectUtils.isNotEmpty(userQueryParam.getName())){
            lambda.eq(UserInfo::getName,userQueryParam.getName());
        }
        if(ObjectUtils.isNotEmpty(userQueryParam.getIdCard())){
            lambda.eq(UserInfo::getIdCard,userQueryParam.getIdCard());
        }
        if(ObjectUtils.isNotEmpty(userQueryParam.getStatus())){
            lambda.eq(UserInfo::getStatus,userQueryParam.getStatus());
        }
        return lambda;
    }

    @ApiOperation(value = "导入用户信息",notes = "导入用户信息")
    @PostMapping("/importData")
    public void importData(MultipartFile file) throws Exception {
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(0);
        importParams.setHeadRows(1);
        importParams.setSheetNum(1);
        List<UserInfo> userInfos = ExcelImportUtil.importExcel(file.getInputStream(), UserInfo.class, importParams);
        System.out.println(JSONObject.toJSONString(userInfos));
    }

    @ApiOperation(value = "获取用户信息不返回密码",notes = "获取用户信息不返回密码")
    @GetMapping("/getIgnorePassword")
    public ResultEntity getIgnorePassword(){
        UserInfo userInfo = new UserInfo();
        userInfo.setId("1");
        userInfo.setUsername("admin");
        userInfo.setPassword("123456");
        return ResultEntity.success(userInfo);
    }

    @ApiOperation(value = "导入图片信息",notes = "导入图片信息")
    @PostMapping("/importImage")
    public ResultEntity importImage(MultipartFile file) throws Exception {
        Map<String, Map<String, XSSFPictureData>> rowMap = new HashMap<>();
        XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
        XSSFSheet sheet = workbook.getSheetAt(0);
        List<XSSFShape> shapes = sheet.getDrawingPatriarch().getShapes();
        for (XSSFShape shape : shapes){
            if (shape instanceof XSSFPicture){
                XSSFPicture picture = (XSSFPicture) shape;
                //获取锚点
                XSSFClientAnchor xssfClientAnchor = (XSSFClientAnchor) picture.getAnchor();
                XSSFPictureData pictureData = picture.getPictureData();
                //获取行列信息
                String row = String.valueOf(xssfClientAnchor.getRow1());
                String col = String.valueOf(xssfClientAnchor.getCol1());
                if (rowMap.containsKey(row)){
                    Map<String, XSSFPictureData> colMap = rowMap.get(row);
                    colMap.put(col, pictureData);
                }else {
                    Map<String, XSSFPictureData> colMap = new HashMap<>();
                    rowMap.put(row, colMap);
                }
                String pic = Base64.getEncoder().encodeToString(pictureData.getData());
                System.out.println(pic);
            }
        }
        return ResultEntity.success();
    }

    @ApiOperation(value = "一对多关系导入",notes = "一对多关系导入")
    @PostMapping("/importModel")
    public ResultEntity importModel(MultipartFile file) throws Exception {
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(0);
        importParams.setHeadRows(2);
        List<UserModel> userModels = ExcelImportUtil.importExcel(file.getInputStream(), UserModel.class, importParams);
        return ResultEntity.success(userModels);
    }
}